package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.model.common.constants.NewsAutoScanConstants;
import com.heima.model.common.constants.WemediaConstants;
import com.heima.model.common.constants.WmNewsMessageConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVo;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {


    @Value("${file.oss.web-site}")
    private String webSite;

    @Autowired
    WmNewsMapper wmNewsMapper;

    @Autowired
    WmUserMapper wmUserMapper;

    @Autowired
    KafkaTemplate kafkaTemplate;

    /**
     * 自媒体文章人工审核
     * @param status 2  审核失败  4 人工审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDto dto) {

        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 先查询
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null
                || wmNews.getStatus().intValue() == 9 ||
                wmNews.getStatus().intValue() == 8){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"文章已审核");
        }

        // 后修改 2 4
        wmNews.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询文章详情带作者
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1 参数检查
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2 查询文章基本信息
        WmNews wmNews = getById(id);
        if (wmNews == null || wmNews.getUserId()==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3 查询文章作者名称
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());

        //4 返回结果
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews, wmNewsVo);
        if (wmUser != null) {
            wmNewsVo.setAuthorName(wmUser.getName());
        }

        ResponseResult result = ResponseResult.okResult(wmNewsVo);
        result.setHost(webSite);
        return result;
    }

    /**
     * 查询审核文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        //1 参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 处理分页参数
        dto.checkParam();
        Integer page = dto.getPage(); // 页码 从1开始

        Integer cpage = (page - 1) * dto.getSize();  // 起始条数 从0开始
        dto.setPage(cpage);

        //2 查询分页数据
        if (StringUtils.isNotBlank(dto.getTitle())) {
            dto.setTitle("%"+dto.getTitle()+"%");
        }
        List<WmNewsVo> newsVoList = wmNewsMapper.findListAndPage(dto);

        //3 查询总记录数
        long count = wmNewsMapper.findListCount(dto);

        //4 封装结果返回
        ResponseResult result = new PageResponseResult(page,
                dto.getSize(), count, newsVoList);

        return result;
    }

    /**
     * 查询需要发布的文章id列表
     * @return
     */
    @Override
    public List<Integer> findRelease() {

        // select id from ....
       List<WmNews> ids=  list( Wrappers.<WmNews>lambdaQuery()
                .in(WmNews::getStatus,4,8)
                .le(WmNews::getPublishTime, new Date())
                .select(WmNews::getId)
        );

        List<Integer> idList =
                ids.stream().map(x -> x.getId()).collect(Collectors.toList());

        return idList;
    }

    /**
     * 根据id查询文章
     * @param id
     * @return
     */
    @Override
    public WmNews findById(Integer id) {
        return getById(id);
    }

    /**
     * 修改文章（状态、拒绝理由、文章articleId）
     *
     * @param wmNews
     * @return
     */
    @Override
    public ResponseResult updateWmNews(WmNews wmNews) {
        boolean flag = updateById(wmNews);
        if (!flag) {
            ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 上下架
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.检查参数
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        //3 判断文章的状态 只有已发布的文章才可以上下架
        if (!wmNews.getStatus().equals(WemediaConstants.WM_NEWS_PUBLISH_STATUS)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章未发布无权上下架");
        }

        //4 执行修改
        wmNews.setEnable(dto.getEnable());
        updateById(wmNews);

        // 同步到APP端文章配置信息 id，enable 0下架  1上架
        if (wmNews.getArticleId() != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("articleId", wmNews.getArticleId());
            map.put("enable", dto.getEnable());

            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,
                    JSON.toJSONString(map));
        }


        //5 返回结果

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 删除文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        // 上架且发布则无法删除
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED)
                && wmNews.getEnable().equals( WemediaConstants.WM_NEWS_UPENABLE)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }

        // 删除文章
        removeById(id);

        // 删除文章和素材的关系
        wmNewsMaterialMapper.delete(
                Wrappers.<WmNewsMaterial>lambdaQuery()
                        .eq(WmNewsMaterial::getNewsId, wmNews.getId()
                        )
        );

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {

        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        // 处理封面图片的前缀
//        String images = wmNews.getImages();
//        StringBuffer sb = new StringBuffer();
//        if (StringUtils.isNotBlank(images)) {
//            String[] split = images.split(",");
//            for (String image : split) {
//                image = webSite + image;
//                sb.append(images).append(",");
//            }
//            images = sb.toString().substring(0,sb.toString().lastIndexOf(","));
//            wmNews.setImages(images);
//        }
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);

        return result;
    }

    /**
     * 自媒体文章发布
     * @param dto
     * @param isSubmit 是否为提交 1 为提交 0为草稿
     * @return
     */
    @Override
    @Transactional
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {
        //1 参数校验
        if (dto == null || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2 保存或修改文章
        WmNews wmNews = new WmNews();
        // 参数封装
        BeanUtils.copyProperties(dto, wmNews);
        // 文章封面类型 -1
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        //处理文章封面
        String images = imageListToStr(dto.getImages(), webSite);
        if (StringUtils.isNotBlank(images)) {
            wmNews.setImages(images);
        }
        saveWmNews(wmNews);



        //3 关联文章和素材的关系（isSubmit=1 提交时关联）
        // 解析文章内容中的图片列表
        List<Map> contentList = JSON.parseArray(dto.getContent(), Map.class);
        List<String> materials = parseContentImages(contentList);

        //3.1 关联文章 内容 和素材的关系
        if (isSubmit == WmNews.Status.SUBMIT.getCode() && materials.size() > 0) {
            saveRelativeInfoForContent(materials, wmNews.getId());
        }

        //3.2 关联文章 封面 和素材的关系
        if (isSubmit == WmNews.Status.SUBMIT.getCode()) {
            saveRelativeInfoForCover(dto, materials,wmNews);
        }

        //4****** 发消息给admin 审核
        Map<String, Integer> map = new HashMap<>();
        map.put("wmNewsId", wmNews.getId());
        kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, JSON.toJSONString(map));


        //5 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    /**
     * 保存文章 封面 和素材关系
     * @param dto 前端参数   # images 图片封面带前缀
     * @param materials 文章内容中的图片列表#无图片前缀
     * @param wmNews 文章对象
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, List<String> materials, WmNews wmNews) {
        //1 获取dto 图片封面
        List<String> images = dto.getImages();

        //2 判断type是否为自动
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {

            int size = materials.size();
            if (size > 0 && size <= 2) { // 单图
                images = materials.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);

            } else if (size > 2) { // 多图
                images = materials.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }else { // 无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            if (images != null) {
                wmNews.setImages(imageListToStr(images, webSite));
            }
            updateById(wmNews);
        }

        //3 执行保存文章封面和素材关系
        if (images != null && images.size() > 0) {
            saveRelativeInfoForImage(images, wmNews.getId());
        }

    }

    /**
     * 保存文章封面和图片关系
     * @param images
     * @param wmNewsId
     */
    private void saveRelativeInfoForImage(List<String> images, Integer wmNewsId) {
        images = images.stream().map( x ->
                x.replace(webSite,"").replace(" ","") )
                .collect(Collectors.toList());

        saveRelativeInfo(images, wmNewsId, WemediaConstants.WM_IMAGE_REFERENCE);
    }

    /**
     * 保存文章 内容和素材关系
     * @param materials  内容图片列表
     * @param wmNewsId 文章id
     */
    private void saveRelativeInfoForContent(List<String> materials, Integer wmNewsId) {
        saveRelativeInfo(materials, wmNewsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }


    @Autowired
    WmMaterialMapper wmMaterialMapper;

    /**
     * 执行保存文章素材关系
     * @param materials 素材URL列表
     * @param wmNewsId 文章id
     * @param type 引用类型  0：内容  1：封面
     */
    private void saveRelativeInfo(List<String> materials, Integer wmNewsId, Short type) {
        // 1 根据url 查询素材对应的id
        List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                .in(WmMaterial::getUrl, materials)
                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId()));

        if (dbMaterials == null || dbMaterials.size() == 0) {
            throw new CustomException(AppHttpCodeEnum.FILE_MATERIAL_ISNULL_ERROR);
        }
        // 2 判断文章素材是否存在
        // dbMaterials(少) 1 2 3  materials（多） 1 2 3 4
        // {"1.jpg":1, "2.jpg":2 ....}
//        HashMap map = new HashMap();
//        for (WmMaterial dbMaterial : dbMaterials) {
//            map.put(dbMaterial.getUrl(), dbMaterial.getId());
//        }
        Map<String, Integer> matreialMap = dbMaterials.stream()
                .collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));

        // 存放素材对应的id
        List<Integer> materialIds = new ArrayList<>();

        for (String url : materials) {
            Integer id = matreialMap.get(url);
            // 数据库的素材被删除
            if (id == null) {
                CustException.cust(AppHttpCodeEnum.FILE_MATERIAL_ISNULL_ERROR);
            }

            materialIds.add(id);
        }


        //3 执行保存(批量保存)
        wmNewsMaterialMapper.saveRelations(materialIds, wmNewsId, type);
    }

    /**
     * 抽取文章内容中的图片url列表
     * @param contentList 内容列表
     * @return
     */
    private List<String> parseContentImages(List<Map> contentList) {
        List<String> materials = new ArrayList<>();

        for (Map<String, String> content : contentList) {
            if (content.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE)) {
                String imageUrl = content.get("value")
                        .replace(webSite,"")
                        .replace(" ","");

                materials.add(imageUrl);
            }
        }

        return materials;
    }

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 保存或修改文章
     * @param wmNews
     */
    private void saveWmNews(WmNews wmNews) {

        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UPENABLE); // 上架

        if (wmNews.getId() == null) {// 新增
            save(wmNews);
        } else { // 修改
            // 删除文章和素材关系
            wmNewsMaterialMapper.delete(
                    Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()
                    )
            );

            updateById(wmNews);
        }
    }

    /**
     * 抽取前端文章封面列表装换成字符串
     * material/2021/1/20210104/1.jpg,material/2021/1/20210104/2.jpg,material/2021/1/20210104/3.jpg
     * @param images
     * @param webSite
     * @return
     */
    private String imageListToStr(List<String> images, String webSite) {
        if (images.size() > 0) {

            return images.toString()
                    .replace("[","")
                    .replace("]","")
                    .replace(webSite,"")
                    .replace(" ","");
        }
        return null;
    }


    /**
         * 查询自媒体文章列表
         * @param dto
         * @return
         */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1 参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        dto.checkParam();


        //2 封装查询条件,执行查询
        LambdaQueryWrapper<WmNews> query = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {// 状态
            query.eq(WmNews::getStatus, dto.getStatus());
        }

        if (StringUtils.isNotBlank(dto.getKeyword())) {// 文章标题
            query.like(WmNews::getTitle, dto.getKeyword());
        }
        if (dto.getChannelId() != null) { // 频道
            query.eq(WmNews::getChannelId, dto.getChannelId());
        }
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {// 发布时间
            query.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }

        //获取登录用户
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        query.eq(WmNews::getUserId, user.getId());

        //创建时间倒序
        query.orderByDesc(WmNews::getCreatedTime);


        IPage<WmNews> pageParam = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmNews> pageResult = page(pageParam, query);


        //3 返回结果（文章封面图片）
        ResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),
                        pageResult.getTotal(), pageResult.getRecords());

        // 处理图片封面
        result.setHost(webSite);

        return result;
    }
}
